//
//  UIs_Animation_Shake_DemoVC.swift
//  APSwift
//
//  Created by jianbo.pei on 2023/10/19.
//

import UIKit

class UIs_Animation_Shake_DemoVC: UIViewController {

    private var textLabel: UILabel!
    private var likeEffectImageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        likeEffectImageView = UIImageView().then({ make in
            view.addSubview(make)
            make.image = UIImage(named: "gb_bullet_like_4")
            make.snp.makeConstraints { make in
                make.center.equalToSuperview()
                make.size.equalTo(200)
            }
        })
        
        textLabel = UILabel().then({ make in
            view.addSubview(make)
            make.text = "x43"
            make.backgroundColor = .lightGray
            make.font = UIFont.systemFont(ofSize: 100)
            make.snp.makeConstraints { make in
                make.centerX.equalTo(likeEffectImageView)
                make.centerY.equalTo(likeEffectImageView.snp.centerY).offset(-120)
            }
        })
        textLabel.transform = CGAffineTransformScale(textLabel.transform, 0.1, 0.1)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        animation()
        UIView.animate(withDuration: 0.66) { [weak self] in
            self?.textLabel.transform = CGAffineTransformIdentity
        } completion: { _ in
            hideTextLabel()
        }
        
        func hideTextLabel() {
            UIView.animate(withDuration: 0.66) { [weak self] in
                guard let self = self else { return }
                self.textLabel.transform = CGAffineTransformScale(self.textLabel.transform, 0.1, 0.1)
            }
        }
    }
    
    /// 按照中心点抖动
    func animation() {
        let animati = CAKeyframeAnimation(keyPath: "transform.rotation")
        // rotation 旋转，需要添加弧度值
        // 角度转弧度
        animati.values = [angle2Radion(angle: 120), angle2Radion(angle: 0)]
        animati.repeatCount = 1
        animati.duration = 0.33
        
        likeEffectImageView.layer.add(animati, forKey: nil)
    }
    
    func angle2Radion(angle: Float) -> Float {
        return angle / Float(180.0 * Double.pi)
    }
    
}


 
extension UIView {
    
    /// 扩展UIView增加抖动方法。使用时，要避免离开页面后方法仍然在调用。
    /// - Parameters:
    ///   - isVertical: 抖动方向（默认是水平方向）
    ///   - times: 抖动次数（默认5次）
    ///   - interval: 每次抖动时间（默认0.1秒）
    ///   - delta: 抖动偏移量
    ///   - completion: 动画结束回调
    public func shake(_ isVertical: Bool = false, _ times: Int = 5, _ interval: TimeInterval = 0.1, _ delta: CGFloat = 2, _ completion: (() -> ())? = nil) {
        UIView.animate(withDuration: interval) {
            var transform: CGAffineTransform?
            if isVertical == true {
                transform = CGAffineTransform(translationX: delta, y: 0)
            } else {
                transform = CGAffineTransform(translationX: 0, y: delta)
            }
            self.layer.setAffineTransform(transform!)
        } completion: {_ in
            if (times == 0) {
                UIView.animate(withDuration: interval) {
                    self.layer.setAffineTransform(CGAffineTransform.identity)
                } completion: { _ in
                    completion?()
                }
            } else {
                self.shake(isVertical, times - 1, interval, -delta, completion)
            }
        }
    }
    
}
